import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, logout, checkLogin } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref({
    id: null,
    username: '',
    email: '',
    userPicture: '',
    bio: '',
    role: 0,
    createdAt: '',
    updatedAt: ''
  })
  
  const isLoggedIn = ref(false)
  const token = ref('')

  const setUserInfo = (info) => {
    userInfo.value = { ...userInfo.value, ...info }
    isLoggedIn.value = true
  }

  const clearUserInfo = () => {
    userInfo.value = {
      id: null,
      username: '',
      email: '',
      userPicture: '',
      bio: '',
      role: 0,
      createdAt: '',
      updatedAt: ''
    }
    isLoggedIn.value = false
    token.value = ''
  }

  const userLogin = async (loginData) => {
    try {
      const result = await login(loginData)
      if (result.success) {
        setUserInfo(result.data)
        if (result.data.token) {
          token.value = result.data.token
        }
        return { success: true, message: result.message }
      } else {
        return { success: false, message: result.message }
      }
    } catch (error) {
      return { success: false, message: '登录失败，请稍后重试' }
    }
  }

  const userLogout = async () => {
    try {
      await logout()
      clearUserInfo()
      return { success: true, message: '退出登录成功' }
    } catch (error) {
      clearUserInfo()
      return { success: true, message: '退出登录成功' }
    }
  }

  const checkLoginStatus = async () => {
    try {
      const result = await checkLogin()
      if (result.success) {
        setUserInfo(result.data)
        return true
      } else {
        clearUserInfo()
        return false
      }
    } catch (error) {
      clearUserInfo()
      return false
    }
  }

  const isAdmin = () => {
    return userInfo.value.role === 1
  }

  const isUser = () => {
    return userInfo.value.role === 0
  }

  const getAvatarUrl = () => {
    if (userInfo.value.userPicture) {
      return userInfo.value.userPicture
    }
    return ''
  }

  const getUserInitial = () => {
    if (userInfo.value.username) {
      return userInfo.value.username.charAt(0).toUpperCase()
    }
    return 'U'
  }

  return {
    userInfo,
    isLoggedIn,
    token,
    setUserInfo,
    clearUserInfo,
    userLogin,
    userLogout,
    checkLoginStatus,
    isAdmin,
    isUser,
    getAvatarUrl,
    getUserInitial
  }
}, {
  persist: true
})
